package cc.mcyx.ychat.fillter

import cc.mcyx.ychat.service.impl.AuthService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Component
class AppFilter : HandlerInterceptor {
    // 无需校验 Token 接口
    private val whitelist = listOf(
        "/api/auth/login"
    )

    @Autowired
    lateinit var authService: AuthService
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        response.addHeader("Access-Control-Allow-Origin", "*")
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE")
        response.addHeader("Access-Control-Allow-Headers", "*")
        if (whitelist.contains(request.requestURI)) return true
        val token = request.getHeader("Authorization") ?: null
        token?.apply { authService.checkTokenEx(this) }
        return true
    }
}